package cn.xiaopeng.mcp.server.csdn.infrastructure.adapter;

import cn.xiaopeng.mcp.server.csdn.domain.adapter.ICSDNPort;
import cn.xiaopeng.mcp.server.csdn.domain.model.ArticleFunctionRequest;
import cn.xiaopeng.mcp.server.csdn.domain.model.ArticleFunctionResponse;
import cn.xiaopeng.mcp.server.csdn.infrastructure.gateway.ICSDNService;
import cn.xiaopeng.mcp.server.csdn.infrastructure.gateway.dto.ArticleRequestDTO;
import cn.xiaopeng.mcp.server.csdn.infrastructure.gateway.dto.ArticleResponseDTO;
import cn.xiaopeng.mcp.server.csdn.type.CSDNApiProperties;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;

/**
 * @author jiangyangang
 * 基础防腐层
 */
@Slf4j
@Component
public class CSDNPort implements ICSDNPort {

    @Resource
    private CSDNApiProperties csdnApiProperties;

    @Resource
    private ICSDNService csdnService;


    @Override
    public ArticleFunctionResponse writeArticle(ArticleFunctionRequest request) throws IOException {
        ArticleRequestDTO articleRequestDTO = new ArticleRequestDTO();
        articleRequestDTO.setTitle(request.getTitle());
        articleRequestDTO.setMarkdowncontent(request.getMarkdowncontent());
        articleRequestDTO.setContent(request.getContent());
        articleRequestDTO.setTags(request.getTags());
        articleRequestDTO.setDescription(request.getDescription());
        articleRequestDTO.setCategories(csdnApiProperties.getCategories());

        Call<ArticleResponseDTO> call = csdnService.saveArticle(csdnApiProperties.getCookie(), articleRequestDTO);
        Response<ArticleResponseDTO> response = call.execute();

        log.info("请求CSDN发帖结果 request={}, response={}", JSONObject.toJSONString(articleRequestDTO), JSONObject.toJSONString(response.body()));

        if (response.isSuccessful()) {
            ArticleResponseDTO articleResponseDTO = response.body();
            if (null == articleResponseDTO) {
                return null;
            };

            ArticleFunctionResponse articleFunctionResponse = new ArticleFunctionResponse();
            articleFunctionResponse.setCode(articleResponseDTO.getCode());
            articleFunctionResponse.setMsg(articleResponseDTO.getMsg());

            articleFunctionResponse.setArticleData(ArticleFunctionResponse.ArticleData.builder()
                    .id(articleResponseDTO.getData().getId())
                    .url(articleResponseDTO.getData().getUrl())
                    .qrcode(articleResponseDTO.getData().getQrcode())
                    .title(articleResponseDTO.getData().getTitle())
                    .description(articleResponseDTO.getData().getDescription())
                    .build()
            );

            return articleFunctionResponse;
        }

        return null;

    }
}
